﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="QueryForm.aspx.cs" Inherits="ZX.WebApp.Extend.QueryForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/reset-fonts-grids/reset-fonts-grids.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/menu/assets/skins/sam/menu.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
    <link type="text/css" rel="stylesheet" href="../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <!--begin custom header content for this example-->
    <style type="text/css">
    .yui-skin-sam table {
	    width: 100%;
    }
    
    #button-example-form fieldset, 
    #button-example-form fieldset div {

        border: 2px groove #ccc;
        margin: .5em;
        padding: .5em;

    }

    .yui-button#pushbutton2 button,
    .yui-button#pushbutton5 button, 
    .yui-button .Add button {
        background: url(../button/assets/add.gif) center center no-repeat;
        text-indent: -4em;
        overflow: hidden;
        padding: 0 .75em;
        width: 2em;
        *margin-left: 4em;   /* IE only */
        *padding: 0 1.75em;  /* IE only */

    }
    
    .yui-button#pushbutton3 button,
    .yui-button#pushbutton6 button, 
    .yui-button#pushbutton9 button {

        padding-left: 2em;
        background: url(../button/assets/add.gif) 10% 50% no-repeat;
    
    }
    #container select,#container input
    {
        width:100%;
        min-width:5em;
    }
    
    
    #toolbar
    {
        border-bottom:1px solid #ccc;
        margin-bottom:3px;
    }
    .form
    {
        padding:5px;
    }
    
    .form select
    {
        width:120px;
    }
    
    
</style>
    <!--end custom header content for this example-->
    <!-- Dependencies -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <!-- OPTIONAL: JSON Utility (for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <!-- OPTIONAL: Calendar (enables calendar editors) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/calendar/calendar-min.js"></script>
    <!-- Source files -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/resize/resize-min.js"></script>

</head>
<body class="yui-skin-sam">
    <div id="toolbar" style="padding: 5px;">
<%--        <button type="button" id="btnOpen" class="yui-button yui-push-button" style="display: none">
            打开方案</button>--%>
        <button type="button" id="btnAddNew" class="yui-button yui-push-button">
        新增</button>
        <button type="button" id="btnDelete" class="yui-button yui-push-button">
        删除</button>
        <button type="button" id="btnSave" class="yui-button yui-push-button">
        保存</button>
        <button type="button" id="btnQuery" class="yui-button yui-push-button">
        <% if (this.GetStringFromQueryString("flag", "1") == "1")
           {%>查询<%}
           else
           { %>设置<%} %></button>
    </div> 
    <div id="data">
    </div>
    <div id="bottom" class="form">
        历史方案:<% =Solution %>
        方案名称:<input type="text" id="SolutionName" /> 是否默认:<input type="checkbox" id="IsDefault" />       </div>
   
    <script type="text/javascript">
        (function () {
        var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

        Event.onDOMReady(function () {
            var layout = new YAHOO.widget.Layout({
                units:  [
                { position: 'top',height: 40, body: 'toolbar', gutter: '1 1 1 1', scroll: null, zIndex: 2 },
                //{ position: 'left', header: '功能模块', width: 250, body: 'left', gutter: '1 5 1 1', collapse: true, scroll: true, zIndex: 1, resize: true },
                {position: 'center', body: 'data', gutter: '1 1', scroll: true },
                { position: 'bottom', height: 35, body: 'bottom', gutter: '1 1'}
            ]
            });
            layout.render();
        });
    })();


    // 字段信息
    var arrFieldInfo = <% =FieldInfo %>,
        arrOperation = [ { Text: "包含", Value: "like"},{ Text: "等于", Value: " = " }, { Text: "大于", Value: ">" }, { Text: "大于且等于", Value: ">=" }, { Text: "小于", Value: "<"},{Text :"小于且等于", Value: "<=" },{Text:"不等于" , Value: "<>"} ],
        arrOrAnd = [ { Text: " ", Value: " " },{ Text: "与", Value: "and" }, { Text: "或", Value: "or" }],
        mDataTable,
        QueryInstance=[<% =strJson %>],
        const_EntityName="<% =EntityName %>",
        const_FunctionId="<% =FunctionID %>",
        const_SolutionList = <% =SolutionList  %>;


        var formatField = function (elCell, oRecord, oColumn, sData) {
                //elCell.innerHTML = (sData === null) ? "N/A" : YAHOO.util.Number.format(sData);
                var str1 = [];
                str1.push("<select name='FieldName'  onchange='ChangeEvent(this);'>");
                str1.push("<option value=''> </option>");
                for (i = 0; i < arrFieldInfo.length; i++) {
                    if(i==0)
                    { continue;}
                    //alert(arrFieldInfo[i].Field+":"+);
                    if(arrFieldInfo[i].Field == oRecord.getData("FieldName")){
                        str1.push("<option value='" + arrFieldInfo[i].Field + "' selected>" + arrFieldInfo[i].THCaption + "</option>");
                    }
                    else{
                        str1.push("<option value='" + arrFieldInfo[i].Field + "'>" + arrFieldInfo[i].THCaption + "</option>");
                    }
                }
                str1.push("</select>");
                elCell.innerHTML = str1.join("");
            };
            var formatOperation = function (elCell, oRecord, oColumn, sData) {
                var str1 = [];
                str1.push("<select name='Operation' onchange='ChangeEvent(this);'>");
                for (i = 0; i < arrOperation.length; i++) {
                   
                   if(arrOperation[i].Value==sData){
                      str1.push("<option value='" + arrOperation[i].Value + "' selected>" + arrOperation[i].Text + "</option>");
                   }else{
                      str1.push("<option value='" + arrOperation[i].Value + "'>" + arrOperation[i].Text + "</option>");
                   }
                } 
                str1.push("</select>");
                
                elCell.innerHTML = str1.join();
            }
            var formatOrand =  function(elCell, oRecord, oColumn, sData) {
                var str1 = [];
                var id = "id"+Math.random();
                str1.push("<select id='"+id+"' onchange='ChangeEvent(this);' name='OrAnd'>");
                for (i = 0; i < arrOrAnd.length; i++) {
                    if(arrOrAnd[i].Value == sData){
                    str1.push("<option value='" + arrOrAnd[i].Value + "' selected>" + arrOrAnd[i].Text + "</option>");
                    }else{
                    str1.push("<option value='" + arrOrAnd[i].Value + "'>" + arrOrAnd[i].Text + "</option>");
                    }
                    
                }
                str1.push("</select>");
                elCell.innerHTML = str1.join("");
            } 
            var formatLeftText = function (elCell, oRecord, oColumn, sData) {
                elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='Left' onchange='ChangeEvent(this);'>";
            }
            
            var formatRightText = function (elCell, oRecord, oColumn, sData) {
                elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='Right' onchange='ChangeEvent(this);'>";
            }

           var formatValueText = function (elCell, oRecord, oColumn, sData) {
                elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='Value' onchange='ChangeEvent(this);'>";
            }
   

    var myDataSource;
    YAHOO.util.Event.addListener(window, "load", function () {
          YAHOO.example.RowDataMod = function () {
 
            var myColumnDefs = [
            //{ key: "Left", label: "左括符", resizeable: true, formatter: formatLeftText },
            //{ key: "FieldName", label: "左括符", resizeable: true },
            { key: "Field", label: "字段名", resizeable: true, formatter: formatField },
            { key: "Operation", label: "操作符", resizeable: true, formatter: formatOperation },
            { key: "Value", label: "值", resizeable: true, formatter: formatValueText },
            { key: "OrAnd", label: "与或", resizeable: true, formatter: formatOrand }
            //{ key: "Right", label: "右括符", resizeable: true, formatter: formatRightText }
          ];

            myDataSource = new YAHOO.util.DataSource([{Left:"",Field:"",Operation:"like",Value: "",OrAnd:" ",Right:""}]);
            myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
            myDataSource.responseSchema = {
                fields: ["FieldName","Left", "Field", "Operation", "Value", "OrAnd","Right"]
            };

            var myDataTable = new YAHOO.widget.DataTable("data",
                myColumnDefs, myDataSource, {selectionMode:"single"});
            mDataTable = myDataTable;
            var i = 1,
            bReverseSorted = false;

            // Track when Column is reverse-sorted, since new data will come in out of order
            var trackReverseSorts = function (oArg) {
                bReverseSorted = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
            };

            myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow); 
	        myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow); 
            myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow); 
            //this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);
            myDataTable.subscribe("checkboxClickEvent", function(oArgs){
                var elCheckbox = oArgs.target;
                var oRecord = this.getRecord(elCheckbox);
                oRecord.setData("iSun_Selected",elCheckbox.checked);
            });

            // Add/update/delete rows as indicated
            var handleClick = function () {
                // Reset sort
                myDataTable.set("sortedBy", null);

                index = myDataTable.getRecordSet()._records.length;
                var entity = [{Left:"",Field:"",Operation:" = ",Value: "",OrAnd:"and",Right:""}];
                myDataTable.addRows(entity, index);

                YAHOO.log("Could not continue due to invalid index.");
            }

             
            var fnDelete = function(){
                 var recordID = myDataTable.getSelectedRows()[0];
                 myDataTable.deleteRow(recordID);
                 //alert(recordID);
            }

            var Save = function ()
            {
                    //setQuery();
                    var list =myDataTable.getRecordSet()._records;
                    var elist = [];
                    for(var i=0;i<list.length;i++)
                    {
                          elist.push(list[i]._oData);
                    }
                   
                    url = "AjaxData/DataSave.aspx";
                    var jsonStr = YAHOO.lang.JSON.stringify(elist);
                    var condition = getCondition();
                    QueryInstance[0].QueryID =document.getElementById("HistorySolution").value; 
                    QueryInstance[0].Condition = condition;
                    QueryInstance[0].SolutionName = document.getElementById("SolutionName").value;
                    QueryInstance[0].IsDefault = document.getElementById("IsDefault").checked?"Y":"N";
                    if(condition=="" )
                    {
                        alert("请设置条件");
                        return;
                    }
                    if(QueryInstance[0].SolutionName=="")
                    {
                        alert("请填查询方案名称");
                        return;
                    }
                    QueryInstance[0].EntityOjbectList = jsonStr;
                    //生成数据
                    jsonStr =  YAHOO.lang.JSON.stringify(QueryInstance[0]);
                    //alert(jsonStr);
                    var SaveUrl =url+"?r=" + Math.random() + "&action=setQuery&functionid="+const_FunctionId+"&entity="+const_EntityName+"&json=" + encodeURI(jsonStr.replace(/&/g,"[A]").replace(/'/g,"''"));
                    YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                        success: function (res) {
                            try {
                                var str = res.responseText;
                                if(str=="1"){
                                    alert("数据保存成功");
                                    parent.closeWin();
                                }
                                else
                                {
                                    alert(str+"\n"+"数据保存失败!");
                                }
                            }
                            catch (e) {
                            }
                            finally {
                            }
                        },
                        failure: function (error) {
                            alert("数据错误：" + error.statusText);
                        }
                    }, null);
                }


            var btnAdd = new YAHOO.widget.Button("btnAddNew");
            btnAdd.on("click", handleClick);
            var btnDelete = new YAHOO.widget.Button("btnDelete");
            btnDelete.on("click",fnDelete);
            //var btnOpen= new YAHOO.widget.Button("btnOpen");
            var btnSave = new YAHOO.widget.Button("btnSave");
            btnSave.on("click",Save);
            var btnQuery = new YAHOO.widget.Button("btnQuery");
            btnQuery.on("click",setQuery);

            return {
                ds: myDataSource,
                dt: myDataTable
            };
        } ();
    });


    //值改变事件
    var ChangeEvent = function(oArgs){
        var f = oArgs.name;
        //alert(f);
        var v = oArgs.value;
        //alert(v);
        setValue(f,v);
    }

    ///f=字段名 v=值
    var setValue = function(f,v){
        var recordID = mDataTable.getSelectedRows()[0];
        var record = mDataTable.getRecord(recordID);
        record._oData[f]=v;    
    }


    var ChangeSolution = function(obj){
        //alert(obj.value);
        for(var i=0;i<const_SolutionList.length;i++){
            if(const_SolutionList[i].QueryId==obj.value)
            {
                SetFormValue(const_SolutionList[i]);
            }
        }
    }
    
    var SetFormValue = function(obj){
        var arr = eval(obj.EntityOjbectList);

        myDataSource.liveData = arr;
        mDataTable.getDataSource().sendRequest(null,
        {success: mDataTable.onDataReturnInitializeTable},
        mDataTable);

       // mDataTable.render();
       document.getElementById("SolutionName").value = obj.SolutionName;
       document.getElementById("IsDefault").checked = QueryInstance[0].IsDefault == "Y" ? true : false;
    }

    var getCondition = function()
    {
        var list =mDataTable.getRecordSet()._records;
        var condition = "";
        //alert(list.length);
        for(var i = 0 ;i<list.length;i++)
        {
            //alert(list[i].Field)
            //condition = condition+ list[i].left+" ";
            condition = condition+ list[i]._oData["FieldName"]+" ";
            condition = condition+ list[i]._oData["Operation"]+" ";
            if(list[i]._oData["Operation"]=="like"){
                condition =condition+ "'%"+list[i]._oData["Value"]+"%' ";
            }
            else
            {
               condition =condition+ "'"+list[i]._oData["Value"]+"' ";
            }
            condition = condition+ list[i]._oData["OrAnd"]+" ";
            //condition = condition+ list[i].Operation+" ";
        }
        return condition;
    }
    var setQuery = function(){
         var flag="<%=this.GetStringFromQueryString("flag","1") %>";
        if(flag=="1"){
            parent.fnQueryRe( encodeURI(getCondition()));
        }
        else
        {
            parent.fnQueryRe( getCondition());
        }
    }

    
    </script>
    <!--END SOURCE CODE FOR EXAMPLE =============================== -->
</body>
</html>
